package gui;


import excecoes.ContaException;
import excecoes.SistemaException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import sistema.Sistema;

import com.trolltech.qt.core.QSize;
import com.trolltech.qt.core.Qt;
import com.trolltech.qt.gui.QDialog;
import com.trolltech.qt.gui.QFileDialog;
import com.trolltech.qt.gui.QHBoxLayout;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QMessageBox;
import com.trolltech.qt.gui.QPixmap;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QScrollArea;
import com.trolltech.qt.gui.QScrollBar;
import com.trolltech.qt.gui.QSpacerItem;
import com.trolltech.qt.gui.QVBoxLayout;
import com.trolltech.qt.gui.QWidget;
import com.trolltech.qt.gui.QSizePolicy.Policy;

/**
 * Janela 
 * 
 * Janela do usuario logado no sistema
 *
 */
public class LoggedWindow extends QDialog {

	private final String IMG_PATH = "ImHereM03/img/";
	private QLabel photo;
	private QVBoxLayout mainLayout;
	private QHBoxLayout lay1;
	private QHBoxLayout lay2;
	private QVBoxLayout friendsLayout;

	private QPushButton messageButton;
	private QPushButton readButton;
	private QPushButton requestsButton;
	private QPushButton inviteButton;
	private QPushButton changeButton;
	private QPushButton deleteButton;
	private QPushButton logoutButton;
	private QPushButton changePhoto;
	
	private List<QPushButton> friendButtons;

	private QScrollArea friends;

	private Sistema sistema;
	private String userName;
	private DeleteAccountDialog deleteDialog;
	private AcceptFriendsDialog requestsDialog;
	
	/**
	 * Construtor
	 * @param userName
	 * @param sistema
	 */
	public LoggedWindow(String userName, Sistema sistema) {
		this.setStyleSheet("QDialog{background: url("+ IMG_PATH + "background.png);}" +
						   "QScrollArea { background:transparent;}" +
						   "QPushButton { background:transparent; " +
						   "qproperty-focusPolicy: NoFocus; }");
		
		this.userName = userName;
		this.sistema = sistema;
		this.friendButtons = new ArrayList<QPushButton>();
		try {
			this.setWindowTitle("I'mHere - Bem vindo, "
					+ sistema.getAtributoUsuario(userName, "nome"));
			this.setWindowIcon(new QIcon(IMG_PATH + "icon.png"));
		} catch (ContaException e) {
			QMessageBox.critical(this, "Erro", "Usuario nao encontrado!");
			this.logout();
		}
		this.setStyleSheet("QWidget{background-image: url("+ IMG_PATH + "background.png);"
				+"font: 9px;}");
		configureLayout();
		this.setFixedSize(650, 400);
		createConnections();
	}

	/**
	 * Ajusta o layout
	 */
	private void configureLayout() {
		this.mainLayout = new QVBoxLayout();
		QSpacerItem spacer1 = new QSpacerItem(0, 0, Policy.Expanding,
				Policy.Minimum);
		configureLayout1();
		configureLayout2();
		this.mainLayout.addLayout(lay1);
		this.mainLayout.addSpacerItem(spacer1);
		this.mainLayout.addLayout(lay2);
		this.setLayout(mainLayout);
	}

	/**
	 * Ajusta layout
	 */
	private void configureLayout1() {
		this.lay1 = new QHBoxLayout();
		QSpacerItem spacer = new QSpacerItem(0, 0, Policy.Expanding);
		this.messageButton = new QPushButton("Enviar mensagem");
		this.readButton = new QPushButton("Ler mensagens");
		this.requestsButton = new QPushButton("Pedidos de amigo");
		this.inviteButton = new QPushButton("Adicionar amigo");
		this.changeButton = new QPushButton("Alterar dados");
		this.deleteButton = new QPushButton("Remover conta");
		this.logoutButton = new QPushButton("Logout");

		lay1.addSpacerItem(spacer);
		lay1.addWidget(messageButton);
		lay1.addWidget(readButton);
		lay1.addWidget(requestsButton);
		lay1.addWidget(inviteButton);
		lay1.addWidget(changeButton);
		lay1.addWidget(deleteButton);
		lay1.addWidget(logoutButton);
	}

	/**
	 * Ajusta Layout
	 */
	private void configureLayout2() {
		this.lay2 = new QHBoxLayout();
		configurePhotoLabel();
		QVBoxLayout photoLayout = new QVBoxLayout();
		photoLayout.addWidget(photo, 0, Qt.AlignmentFlag.AlignCenter);
		photoLayout.addWidget(changePhoto, 0, Qt.AlignmentFlag.AlignCenter);
		this.changePhoto.setFixedSize(changePhoto.size());
		configureFriends();
		QSpacerItem spacer = new QSpacerItem(0, 0, Policy.Expanding,
				Policy.Expanding);
		photoLayout.addSpacerItem(spacer);
		lay2.addLayout(photoLayout);
		lay2.addSpacerItem(spacer);
		lay2.addWidget(friends, 0, Qt.AlignmentFlag.AlignCenter);
	}

	/**
	 * Ajusta foto
	 */
	private void configurePhotoLabel() {
		this.photo = new QLabel(this);
		this.photo.move(13, 10);
		QPixmap pm = new QPixmap(IMG_PATH + "photo_default.png");
		this.photo.setPixmap(pm);
		//this.photo.setFixedSize(this.photo.size());
		this.changePhoto = new QPushButton("Alterar Imagem", this);
		this.changePhoto.move(5, 95);
	}
	
	/**
	 * Widget de amigos
	 */
	private void configureFriends() {
		this.friends = new QScrollArea(this);
		this.friends.setVerticalScrollBar(new QScrollBar());
		this.friends.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded);
		this.friends.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded);
		this.friends.setWidgetResizable(true);
		QWidget widget = new QWidget(this.friends);
		widget.setStyleSheet("background: transparent");
		this.friendsLayout = new QVBoxLayout();
		/*
		 * TEste
		 */
		Iterator<String> friends;
		try {
			friends = sistema.getListaAmigos(userName).listIterator();
			while (friends.hasNext()) {
				String friend = friends.next();
				QPushButton friendButton = new QPushButton();
				friendButton.setText(sistema.getAtributoUsuario(friend, "nome"));
				friendButton.setStyleSheet(getStyle(IMG_PATH + sistema.getAtributoUsuario(friend, "foto")));
				friendsLayout.addWidget(friendButton);
			}
		} catch (ContaException e) {
			QMessageBox.critical(this, "Erro", e.getMessage());
			this.logout();
		}
		this.friends.setFixedSize(210, 350);
		widget.setLayout(this.friendsLayout);
		this.friends.setWidget(widget);
	}

	@SuppressWarnings("unused")
	private void change() {

	}
	
	/**
	 * Configura um styleSheet
	 * 
	 * @param imagePath
	 * @return
	 */
	private String getStyle(String imagePath){
		return "background:transparent;" +
        "qproperty-icon:url(" + imagePath + ");" +
        "min-height:47px;" +
        "min-width:160px;" +
        "max-height:47px;" +
        "max-width:160px;" +
        "qproperty-iconSize: 43px 36px;";
		
	}

	@SuppressWarnings("unused")
	/**
	 * Altera a imagem
	 */
	private void changePhoto() {
		String fileName = QFileDialog.getOpenFileName();
		QPixmap pm = new QPixmap(fileName);
		

		if (!pm.isNull())
			this.photo.setPixmap(pm);
	}

	/**
	 * Desloga
	 */
	private void logout() {
		System.out.println("xau");
		try {
			sistema.logout(userName);
		} catch (SistemaException e) {
			QMessageBox.critical(this, "Erro", e.getMessage()
					+ "\nSaindo agora...");
		} finally {
			this.close();
		}
	}
	
	/**
	 * Remove conta
	 */
	private void delete() {
		this.deleteDialog = new DeleteAccountDialog();
		deleteDialog.okButton.clicked.connect(this, "deleteAccount()");
		this.deleteDialog.exec();
	}
	
	/**
	 * Atualiza os dados
	 */
	private void updateData() {
		ChangeAccountData win;
		try {
			win = new ChangeAccountData(this,this.userName,sistema);
			win.exec();
		} catch (ContaException e) {
			QMessageBox.critical(this, "Erro", e.getMessage());
		}
	}
	
	/**
	 * Ve os pedidos de amigo
	 */
	private void seeRequests() {
		this.requestsDialog = new AcceptFriendsDialog(this.sistema, this.userName);
		this.requestsDialog.exec();
	}
	
	/**
	 * Finaliza a remocao da contacao
	 * @throws ContaException
	 * @throws IOException
	 */
	private void deleteAccount() throws ContaException, IOException{
		this.deleteDialog.close();
		this.close();
		sistema.removerUsuario(this.userName);
		sistema.encerrarSistema();
	}
	
	
	@SuppressWarnings("unused")
	/**
	 * Envia uma mensagem de email ou SMS
	 */
	private void sendMessage() {
		MessengerWidget message = new MessengerWidget(sistema, userName);
		message.show();
	}
	
	@SuppressWarnings("unused")
	/**
	 * Convida um amigo
	 */
	private void invite() {
		InviteWindow invite = new InviteWindow(sistema, userName);
		invite.exec();
	}

	/**
	 * Cria as conexoes necessarias para os botoes
	 */
	private void createConnections() {
		this.logoutButton.clicked.connect(this, "logout()");
		this.changeButton.clicked.connect(this, "updateData()");
		this.deleteButton.clicked.connect(this, "delete()");
		this.changePhoto.clicked.connect(this, "changePhoto()");
		this.changePhoto.clicked.connect(this, "changePhoto()");
		this.messageButton.clicked.connect(this, "sendMessage()");
		this.inviteButton.clicked.connect(this, "invite()");
		this.requestsButton.clicked.connect(this, "seeRequests()");
	}

}
